package com.xihespace.forestryapp.utils.gson;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

public class GsonUtils {

    public final static Gson mGson = new Gson();

    /**
     * 将JsonArray的String数组转换成List<String>
     *
     * @param jsonArray
     * @return
     */
    public static List<String> gsonFormatToList(String jsonArray) {
        return mGson.fromJson(jsonArray, new TypeToken<List<String>>() {

        }.getType());
    }

    /**
     * 将List<String>转换成JsonArrayString数组
     *
     * @param array
     * @return
     */
    public static String listStringFormatJsonArray(List<String> array) {
        return mGson.toJson(array, new TypeToken<List<String>>() {

        }.getType());
    }

    /**
     * @param modifier 需要剔除的修饰符
     * @return
     */
    public static Gson rejectModifier(int... modifier) {
        return new GsonBuilder().excludeFieldsWithModifiers(modifier).create();
    }

    public static Gson rejectFieldAndClass(String[] fields, Class<?>[] classes) {
        List<ExclusionStrategy> exclusionStrategies = new ArrayList<>();
        if (fields != null && fields.length != 0) {
            for (String field : fields) {
                exclusionStrategies.add(new ExclusionStrategy() {
                    @Override
                    public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                        return fieldAttributes.getName().equals(field);
                    }

                    @Override
                    public boolean shouldSkipClass(Class<?> clazz) {
                        return false;
                    }
                });
            }
        }
        if (classes != null && classes.length != 0) {
            for (Class<?> aClass : classes) {
                exclusionStrategies.add(new ExclusionStrategy() {
                    @Override
                    public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                        return false;
                    }

                    @Override
                    public boolean shouldSkipClass(Class<?> clazz) {
                        return clazz.getName().equals(aClass.getName());
                    }
                });
            }
        }
        return new GsonBuilder().setExclusionStrategies(exclusionStrategies.toArray(new ExclusionStrategy[0])).create();
    }
}
